<!--
 * @author  dumeng
-->
<template>
  <div class="collect-create">
    <div class="collect-create-title">新建/编辑</div>
    <section v-loading="loading" class="collect-create-main">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="180px"
        class="form"
      >
        <el-form-item label="活动名称" prop="solicitationName">
          <el-input v-model="form.solicitationName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动时间" prop="hdTime">
          <el-date-picker
            v-model="form.hdTime"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
            :style="{width:'100%'}"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-form-item>
        <el-form-item label="引导图" prop="solicitationImage" required>
          <image-upload
            :key="uploadFile.imagecropperKey"
            v-model="form.solicitationImage"
            :preview-id="uploadFile.viewId"
            :forever="true"
            :width="702"
            :view="uploadFile.view"
            :height="310"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>
        <el-form-item label="活动详情" prop="eventDetails">
          <tinymce
            v-if="showtinymce"
            v-model="form.eventDetails"
            :height="300"
          />
        </el-form-item>
        <el-form-item label="是否允许自主上传作品" prop="isAutonomyUpload">
          <el-radio-group v-model="form.isAutonomyUpload">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="作品是否需要审核" prop="isAudit">
          <el-radio-group v-model="form.isAudit">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="form.isAutonomyUpload === '1'">
          <el-form-item label="投稿时间" prop="tgTime">
            <el-date-picker
              v-model="form.tgTime"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              clearable
              :style="{width:'100%'}"
              type="datetimerange"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
            />
          </el-form-item>
        </template>
        <el-form-item v-else label="不允许自主上传原因" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" autosize placeholder="请输入不允许自主上传原因" />
        </el-form-item>

        <el-form-item label="展示范围">
          <el-radio-group v-model="form.displayRange">
            <el-radio
              v-for="(item, index) in dict.ZJZSFW"
              :key="index"
              :label="item.dictValue"
            >{{ item.dictName }}
            </el-radio>
          </el-radio-group>

        </el-form-item>
        <el-form-item label="参与范围">
          <el-radio-group v-model="form.authorRange">
            <el-radio
              v-for="(item, index) in dict.ZJCYFW"
              :key="index"
              :label="item.dictValue"
            >{{ item.dictName }}
            </el-radio>
          </el-radio-group>

        </el-form-item>

      </el-form>
    </section>
    <section class="collect-create-footer">
      <el-button style="padding: 10px 30px" @click="() => {$router.back();}">取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import { mapGetters } from 'vuex'
import {
  getDictByCode,
  insert,
  update,
  get
} from '../api/index'
import Tinymce from '@/components/Tinymce'
import elDragDialog from '@/directive/el-drag-dialog'

export default {
  name: 'Zjhdmanage',
  components: { ImageUpload, Tinymce },
  directives: { elDragDialog },
  data() {
    return {
      loading: false,
      showtinymce: false,
      form: {
        id: '',
        solicitationName: '',
        tgTime: '',
        hdTime: '',
        solicitationImage: '',
        eventDetails: '',
        isAutonomyUpload: '1',
        remarks: '',
        isAudit: '1',
        displayRange: '',
        authorRange: ''
      },
      rules: {
        solicitationName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '请输入不允许自主上传原因', trigger: 'blur' },
          { min: 1, max: 2000, message: '长度在 1 到 2000 个字符', trigger: 'blur' }
        ],
        tgTime: [
          { required: true, message: '请选择投稿时间', trigger: 'change' }
        ],
        hdTime: [
          { required: true, message: '请选择活动时间', trigger: 'change' }

        ],
        eventDetails: [
          { required: true, message: '请输入活动详情', trigger: 'blur' }
        ],
        solicitationImage: [
          { required: true, message: '请上传引导图', trigger: 'change' }
        ],
        isAutonomyUpload: [
          { required: true, message: '请选择是否允许自主上传作品', trigger: 'change' }
        ],
        isAudit: [
          { required: true, message: '请选择作品是否需要审核', trigger: 'change' }
        ]
      },
      state: 'create',
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: false,
        accept: '',
        fileType: '',
        fileIndex: 0
      },
      dict: {
        ZJZSFW: [], // 展示范围
        ZJCYFW: [] // 参与范围
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    if (this.$route.query.type === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
        return
      }
      this.getData(this.$route.query.i)
    } else {
      this.showtinymce = true
    }
  },
  methods: {
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0]
            .list : []
        }).catch(error => {
          reject(error)
        })
      })
    },
    CleanPastedHTML(input) {
      if (!input) {
        return ''
      }
      input = input.replace(/<\/?[^>]*>/g, '') // 去除HTML tag
      input = input.replace(/(\r)/ig, '')
      input = input.replace(/(\n)/ig, '')
      input = input.replace(/(\t)/ig, '')
      input = input.replace(/ /ig, '')// 去掉
      return input.replace(/&(.*?);/ig, '')
    },
    onSubmint() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const params = Object.assign({}, this.form)
            params['submissionStartTime'] = params.tgTime[0]
            params['submissionEndTime'] = params.tgTime[1]
            params['activityStartTime'] = params.hdTime[0]
            params['activityEndTime'] = params.hdTime[1]
            delete params.hdTime
            delete params.tgTime
            if (this.form.isAutonomyUpload === '1') {
              if (new Date(params['submissionStartTime']).getTime() < new Date(params['activityStartTime']).getTime()) {
                this.$message({
                  title: '提示',
                  message: '投稿开始时间不得早于活动开始时间',
                  type: 'warning',
                  duration: 2000
                })
                return
              }
              if (new Date(params['submissionEndTime']).getTime() > new Date(params['activityEndTime']).getTime()) {
                this.$message({
                  title: '提示',
                  message: '投稿结束时间不得大于活动结束时间',
                  type: 'warning',
                  duration: 2000
                })
                return
              }
            }
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            return new Promise((resolve, reject) => {
              insert(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.back()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const params = Object.assign({}, this.form)
            params['submissionStartTime'] = params.tgTime[0]
            params['submissionEndTime'] = params.tgTime[1]
            params['activityStartTime'] = params.hdTime[0]
            params['activityEndTime'] = params.hdTime[1]
            delete params.hdTime
            delete params.tgTime
            if (this.form.isAutonomyUpload === '1') {
              if (new Date(params['submissionStartTime']).getTime() < new Date(params['activityStartTime']).getTime()) {
                this.$message({
                  title: '提示',
                  message: '投稿开始时间不得早于活动开始时间',
                  type: 'warning',
                  duration: 2000
                })
                return
              }
              if (new Date(params['submissionEndTime']).getTime() > new Date(params['activityEndTime']).getTime()) {
                this.$message({
                  title: '提示',
                  message: '投稿结束时间不得大于活动结束时间',
                  type: 'error',
                  duration: 2000
                })
                return
              }
            }
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            return new Promise((resolve, reject) => {
              update(params).then(() => {
                this.dialogVisible = false
                // eslint-disable-next-line no-undef
                loading.close()
                this.$message({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.back()
              }).catch(error => {
                reject(error)
                // eslint-disable-next-line no-undef
                loading.close()
              })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            if (key === 'tgTime') {
              if (data['submissionStartTime'] && data['submissionEndTime']) {
                this.form[key] = [data['submissionStartTime'], data['submissionEndTime']]
              }
            } else if (key === 'hdTime') {
              if (data['activityStartTime'] && data['activityEndTime']) {
                this.form[key] = [data['activityStartTime'], data['activityEndTime']]
              }
            } else {
              this.form[key] = data[key]
            }
          }
          this.uploadFile.viewId = data.solicitationImage
          this.showtinymce = true
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'y+': date.getFullYear().toString(), // 年
        'M+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'm+': date.getMinutes().toString(), // 分
        's+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
        }
      }
      return fmt
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">

.collect-create {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .collect-create-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: "";
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .collect-create-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
      margin-bottom: 10px;
    }

    .collect-image {
      .el-card__header {
        padding-top: 8px;
        padding-bottom: 8px;
      }
    }

    .images-item {
      position: relative;
      margin-bottom: 10px;

      .upload-img {
        width: 100%;
        height: 160px;
        display: block;
      }

      .el-input {
        display: block;
      }

      .custom-uploader {
        width: 100%;
        display: block;

        .icon-wrap {
          width: 100%;
          height: 160px;
        }
      }

      .el-button {
        position: absolute;
        right: 10px;
        top: 0;
        color: #fff;

        i {
          background: rgba(0, 0, 0, 0.4);
          border-radius: 50%;
          padding: 2px;
        }

        &.image-index-move {
          right: 40px;
        }
      }
    }

    .images-add {
      color: $mainColor;
      font-size: 14px;
      padding-left: 80px;
      cursor: pointer;
      margin-bottom: 20px;
    }

    .upload-img {
      width: 100%;
      height: 160px;
    }

    .attachment-item {
      margin-bottom: 10px;

      .item-btn {
        font-size: 20px;
        cursor: pointer;
      }

      .video-item {
        position: relative;
        cursor: pointer;

        .el-button {
          position: absolute;
          right: 10px;
          top: 0;
          color: #fff;

          i {
            background: rgba(0, 0, 0, 0.4);
            border-radius: 50%;
            padding: 2px;
          }

          &.video-index-move {
            right: 40px;
          }
        }
      }
    }
  }

  .collect-create-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }

  .image-upload-dialog {
    .icon-wrap {
      width: 300px;
      height: 160px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(247, 247, 248, 1);
      border: 1px solid rgba(226, 227, 232, 1);
      border-radius: 4px;

      .avatar-uploader-icon {
        font-size: 48px;
        color: #dadada;
        width: 300px;
        text-align: center;
      }
    }

    .upload-img {
      display: block;
      width: 300px;
      height: 160px;
      border-radius: 4px;
    }
  }
}
</style>
<style lang="scss">

.collect-create {
  .classify-tree-con {
    position: relative;
    height: 400px;
    overflow: hidden;

    .classify-tree-con-scrollbar {
      overflow: hidden;

      .el-scrollbar__wrap {
        max-height: 381px;
      }
    }

    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      width: 100%;

      .tree-node-txt {
        flex: 1;
      }
    }
  }

  .el-tag--medium {
    line-height: 32px;
    height: 32px;

    & + .el-tag--medium {
      margin-left: 10px;
    }
  }
}
</style>
